import {Component, OnInit, ViewChild} from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {DatePipe} from '@angular/common';
import {NzModalService} from 'ng-zorro-antd/modal';

import {UsedStoreZservice} from '../../used-store-zservice';
import {orderStateArrs} from '../../used-store-manage.pipe';
import {PermissionService} from '../../../../service/permission.service';
import { CommonService } from 'src/app/services-common/common.service';
import { defalutImg } from 'src/app/comm';

@Component({
  selector: 'app-used-order-list',
  templateUrl: './used-order-list.component.html',
  styleUrls: ['./used-order-list.component.scss'],
  providers: [DatePipe]
})
export class UsedOrderListComponent implements OnInit {
  @ViewChild('followUpRef') followUpRef: any;

  fallback: string = defalutImg;

  // 路由缓存恢复时
  static updateCache: any = null;
  isCollapse: boolean = true;

  seachParams: any = {
    orderNum: '', // 订单号
    renewalNo: '', // 关联回收单号
    goods: '', // 包含商品
    consignee: '', // 收货人
    expressNum: '', // 物流单号
    cidList: [], // 推广渠道
    createTime: '', // 下单开始时间
    endTime: '', // 下单结束时间
    beginPayTime: '', // 付款结束时间
    endPayTime: '', // 付款结束时间
    beginShipTime: '', // 发货结束时间
    endShipTime: '', // 发货结束时间
    supplierIdList: [] // 货主(供应商)
  };
  // 状态options
  orderStateOptions: any = [...orderStateArrs];
  stateSelected: any = [];
  // 渠道options
  channelOptions: any = [];
  channelSelected: any = [];
  // 用户身份
  userTypeSelected: any = [];
  // 下单时间
  creatDates: any = [];
  // 付款时间
  payDates: any = [];
  // 发货时间
  shipDates: any = [];

  // 物流options
  logisticsOptions: any = [];

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // 批量审核
  isVisible: boolean = false;
  examineForm!: FormGroup;

  // 跟进 Modal
  initParams: any = {
    type: 1, // type  1、订单 2、售后 3、客户 4、出库 5、直降 6、退税 7、机器 8、商品
    modelId: 2, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收
    relationInformation: ''
  };

  // Table check
  checked = false;
  tableDisabled = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  /************************************ Table Checked START ************************************ */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData
      .filter((ele) => ele.status == 3)
      .forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.listOfCurrentPageData.filter((ele) => ele.status == 3);
    this.checked = listOfEnabledData.every(({id}) => this.setOfCheckedId.has(id));
    this.tableDisabled = listOfEnabledData.every(({status}) => status != 3);
    this.indeterminate = listOfEnabledData.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  /************************************ Table Checked END ************************************** */

  // 推广渠道list
  extensionOptions: any = [];

  // 子订单Modal
  isSonVisible: boolean = false;
  sonTableDta: any = [];

  // 货主options（供应商）
  supplierOptions: any = [];
  supplierSelected: any = [];

  /**
   * 快捷筛选
   * 待操作订单————3:待审核、7:待发货、5:审核通过、6:排队发货
   * 有效订单————0:有效、2:待付款、3:待审核、5:审核通过、6:排队发货、7:待发货、8:待收货、13:售后中、14:全部退货、9:交易完成
   * ----------------------------------------------------------------------------------------------------
   */
  quickScreenStatus: any = [
    {value: '', label: '全部'},
    {value: '3,5,6,7', label: '待操作订单'},
    {value: '0,2,3,5,6,7,8,9,13,14', label: '有效订单'}
  ];
  quickScreenSelected: string = '';

  constructor(
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private message: NzMessageService,
    private modal: NzModalService,
    private services: UsedStoreZservice,
    private commonService: CommonService,
    public permissionService: PermissionService
  ) {
  }

  ngOnInit(): void {
    this.getDictListData();
    this.queryExtension();
    this.querySupplierOptions();

    this.examineForm = this.fb.group({
      auditDesc: ['', [Validators.required]]
    });

    UsedOrderListComponent.updateCache = () => {
      this.getDictListData();
      this.queryExtension();
      this.querySupplierOptions();
      this.loadTable();
    };

    this.loadTable();
  }

  // 查询货主
  async querySupplierOptions() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.services.querySupplierList(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.supplierOptions = records.filter((item: any) => item.name) || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 查询 推广渠道cid
  async queryExtension() {
    this.extensionOptions = await this.commonService.getDictList('iDiy_extension_channel');
  }

  // 查询渠道list
  async getDictListData() {
    const res: any = await this.services.dictListData('channel');
    if (res.code == 0) {
      const {list} = res.data || {};
      this.channelOptions = list || [];
    } else {
      this.channelOptions = [];
    }
  }

  // 查询物流list
  async getLogisticsListData() {
    const res: any = await this.services.dictListData('logistics_company');
    if (res.code == 0) {
      const {list} = res.data || {};
      this.logisticsOptions = list || [];
    } else {
      this.logisticsOptions = [];
    }
  }

  async loadTable() {
    let params = {
      ...this.seachParams,
      status: this.stateSelected.join(','),
      platform: this.channelSelected.join(','),
      userType: this.userTypeSelected.join(','),
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    };
    this.tableParams.tableLoading = true;
    const res: any = await this.services.queryMallOrderList(params);
    this.tableParams.tableLoading = false;

    if (res.code == 0) {
      const {records, total} = res.data || {};
      this.tableData = records || [];
      this.tableParams.total = total || 0;

      
    } else {
      this.message.error(res.message);
    }
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.seachParams) {
      if (Object.prototype.toString.call(this.seachParams[key]) === '[object Array]') {
        this.seachParams[key] = [];
      } else {
        this.seachParams[key] = '';
      }
    }
    this.creatDates = []; // 下单时间
    this.payDates = []; // 付款时间
    this.shipDates = []; // 发货时间
    this.stateSelected = []; // 状态
    this.channelSelected = []; // 状态
    this.userTypeSelected = []; // 用户身份
    this.supplierSelected = []; // 货主
    this.quickScreenSelected = ''; // 快捷状态

    this.setOfCheckedId.clear();
    this.tableParams.page = 1;
    this.loadTable();
  }

  /**
   * onTimeChange
   * @param result
   * @param num 0：下单，1：付款，2：发货
   */
  onTimeChange(result: any, num: number) {
    let startT = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    let endT = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
    switch (num) {
      case 0:
        this.seachParams.createTime = startT;
        this.seachParams.endTime = endT;
        break;
      case 1:
        this.seachParams.beginPayTime = startT;
        this.seachParams.endPayTime = endT;
        break;
      case 2:
        this.seachParams.beginShipTime = startT;
        this.seachParams.endShipTime = endT;
        break;
    }
  }

  showModal() {
    this.examineForm.reset();
    if (!this.setOfCheckedId.size) {
      this.message.warning('请先选择所需操作项');
      return;
    }
    this.isVisible = true;
  }

  handleCancel() {
    this.isVisible = false;
  }

  /**
   * 审核
   * @param status 4：不通过，5：通过
   */
  async submitForm(status: number) {
    this.requiredChange(status);
    if (this.examineForm.valid) {
      let params = {
        ids: [...this.setOfCheckedId],
        status: status,
        auditDesc: this.examineForm.get('auditDesc')?.value || ''
      };

      const res: any = await this.services.examineOrderData(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.loadTable();
        this.setOfCheckedId.clear();
        this.isVisible = false;
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.examineForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  requiredChange(num: number): void {
    if (num == 5) {
      this.examineForm.get('auditDesc')!.clearValidators();
      this.examineForm.get('auditDesc')!.markAsPristine();
    } else {
      this.examineForm.get('auditDesc')!.setValidators(Validators.required);
      this.examineForm.get('auditDesc')!.markAsDirty();
    }
    this.examineForm.get('auditDesc')!.updateValueAndValidity();
  }

  // 导出
  exportInterface() {
    let params = {
      ...this.seachParams,
      status: this.stateSelected.join(','),
      platform: this.channelSelected.join(','),
      userType: this.userTypeSelected.join(','),
      page: 1,
      pageSize: 1000000
    };

    for (let key in params) {
      if (params[key] === null) {
        params[key] = '';
      }

      if (Array.isArray(params[key])) {
        params[key] = params[key].length ? params[key].join(',') : '';
      }
    }
    this.services.orderExportData(params).subscribe((res: any) => {
      // console.log('res');
    }, (error: any) => {
      window.open(error.url, '_self');
    });
  }

  exportTable() {
    if (!this.tableData.length) {
      this.message.warning('当前数据为空');
      return;
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '<b>确认导出？</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.exportInterface();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  // 跟进
  followModal(item: any) {
    this.initParams.relationInformation = item.orderNum;
    this.followUpRef.isModelVisible = true;
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 渠道filter
  channelFilter(channelId: any) {
    if (channelId && this.channelOptions.length) {
      let tempObj = this.channelOptions.find((item: any) => {
        return item.content == channelId;
      });
      return tempObj?.name || '-';
    } else {
      return '-';
    }
  }

  // 商品Filter
  goodsFilter(goods: any) {
    if (goods) {
      let tempArr = goods.split(';');
      return tempArr || [];
    } else {
      return '-';
    }
  }

  // Dict类型转化文字
  dictTextFilter(typeVal: String, arr: any) {
    let tmpObj: any = {};
    if (arr && arr.length) {
      tmpObj = arr.find((item: any) => item.content == typeVal);
    }

    return tmpObj?.name || '-';
  }

  // 收货人单数快捷查询
  quantityNumSearch(item: any) {
    this.seachParams.consignee = item.consignee || '';
    this.tableParams.page = 1;
    this.loadTable();
  }

  // 子订单Modal
  showChildModal(item: any) {
    this.sonTableDta = item?.oldList || [];
    this.isSonVisible = true;
  }

  // 多选Select Change
  multipleSelectChange(result: any, keyStr: string) {
    this.seachParams[keyStr] = result.join(',');
  }

  // 快捷选择筛选
  quickScreenChange(val: any) {
    this.stateSelected = val ? val.split(',').map((m: any) => +m) : [];
    this.tableParams.page = 1;
    this.loadTable();
  }
}
